import http from '@/utils/request.js'

// ========================================
// 历史记录查询 API
// ========================================

// 获取用户对话记录（支持过滤）
export const getUserConversations = ({
  startDate,
  endDate,
  model,
  page = 1,
  pageSize = 20
} = {}) => {
  const payload = { page, pageSize }
  if (startDate) payload.startDate = startDate
  if (endDate) payload.endDate = endDate
  if (model) payload.model = model
  
  return http.post('/qa/user-conversations', payload)
}

// 获取用户问答记录列表
export const getUserQARecords = ({
  startDate,
  endDate,
  model,
  page = 1,
  pageSize = 20
} = {}) => {
  const payload = { page, pageSize }
  if (startDate) payload.startDate = startDate
  if (endDate) payload.endDate = endDate
  if (model) payload.model = model
  
  return http.post('/qa/user-records', payload)
}

// 获取问答列表（分页）
export const getQAList = (page = 1, pageSize = 10) => {
  return http.get('/qa', { page, pageSize })
}

// 获取会话列表
export const getSessions = () => http.get('/qa/sessions')

// 获取特定会话详情
export const getSessionDetail = (sessionId) => http.get(`/qa/sessions/${sessionId}`)

// 获取会话消息历史
export const getSessionMessages = (sessionId) => http.get(`/qa/sessions/${sessionId}/messages`)

// 删除会话
export const deleteSession = (sessionId) => {
  return http.delete(`/qa/sessions/${sessionId}`)
}

// 删除会话（无需权限）
export const deleteSessionNoAuth = (sessionId) => {
  return http.delete(`/qa/sessions/${sessionId}/no-auth`)
}

// 更新会话标题
export const updateSessionTitle = (sessionId, title) => {
  return http.put(`/qa/sessions/${sessionId}`, { title })
}

// 简化版：更新会话信息（统一入口）
export const updateSession = ({ sessionId, sessionTitle, sessionStatus, metadata } = {}) => {
  const payload = { sessionId }
  if (sessionTitle) payload.sessionTitle = sessionTitle
  if (sessionStatus) payload.sessionStatus = sessionStatus
  if (metadata) payload.metadata = metadata
  return http.post('/qa/sessions/update', payload)
}

// 清空所有会话
export const clearAllSessions = () => {
  return http.delete('/qa/sessions')
}

// ========================================
// 统计信息 API
// ========================================

// 获取用户统计信息
export const getUserStats = () => {
  return http.get('/qa/user-stats')
}

// 获取模型使用统计
export const getModelUsageStats = ({
  startDate,
  endDate
} = {}) => {
  const params = {}
  if (startDate) params.startDate = startDate
  if (endDate) params.endDate = endDate
  
  return http.get('/qa/model-stats', params)
}

// 获取知识库使用统计
export const getKnowledgeBaseUsageStats = ({
  startDate,
  endDate,
  knowledgeBaseId
} = {}) => {
  const params = {}
  if (startDate) params.startDate = startDate
  if (endDate) params.endDate = endDate
  if (knowledgeBaseId) params.knowledgeBaseId = knowledgeBaseId
  
  return http.get('/qa/knowledgebase-stats', params)
}

// ========================================
// 导出功能 API
// ========================================

// 导出对话记录
export const exportConversations = ({
  startDate,
  endDate,
  model,
  format = 'json'
} = {}) => {
  const payload = { format }
  if (startDate) payload.startDate = startDate
  if (endDate) payload.endDate = endDate
  if (model) payload.model = model
  
  return http.post('/qa/export-conversations', payload)
}

// 导出会话记录
export const exportSessions = ({
  startDate,
  endDate,
  format = 'json'
} = {}) => {
  const payload = { format }
  if (startDate) payload.startDate = startDate
  if (endDate) payload.endDate = endDate
  
  return http.post('/qa/export-sessions', payload)
}

// ========================================
// 工具函数
// ========================================

// 格式化日期为ISO字符串
export const formatDateToISO = (date) => {
  if (typeof date === 'string') {
    return new Date(date).toISOString()
  }
  return date.toISOString()
}

// 创建日期范围查询参数
export const createDateRange = (startDate, endDate) => {
  return {
    startDate: formatDateToISO(startDate),
    endDate: formatDateToISO(endDate)
  }
}

// 获取最近7天的日期范围
export const getLast7DaysRange = () => {
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 7)
  
  return createDateRange(startDate, endDate)
}

// 获取最近30天的日期范围
export const getLast30DaysRange = () => {
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  
  return createDateRange(startDate, endDate)
}

// 获取本月的日期范围
export const getCurrentMonthRange = () => {
  const now = new Date()
  const startDate = new Date(now.getFullYear(), now.getMonth(), 1)
  const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
  
  return createDateRange(startDate, endDate)
}

// 格式化时间显示
export const formatTimeDisplay = (dateString) => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now - date
  
  // 小于1分钟
  if (diff < 60000) {
    return '刚刚'
  }
  
  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  
  // 小于24小时
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  
  // 小于30天
  if (diff < 2592000000) {
    return `${Math.floor(diff / 86400000)}天前`
  }
  
  // 超过30天，显示具体日期
  return date.toLocaleDateString('zh-CN')
}

// 格式化会话标题
export const formatSessionTitle = (messages) => {
  if (!messages || messages.length === 0) {
    return '新会话'
  }
  
  // 取第一条用户消息作为标题
  const firstUserMessage = messages.find(msg => msg.role === 'user')
  if (firstUserMessage) {
    const content = firstUserMessage.content
    return content.length > 20 ? content.substring(0, 20) + '...' : content
  }
  
  return '新会话'
}

// 统计会话消息数量
export const countSessionMessages = (messages) => {
  if (!messages) return 0
  return messages.length
}

// 获取会话最后活跃时间
export const getSessionLastActiveTime = (messages) => {
  if (!messages || messages.length === 0) {
    return null
  }
  
  const lastMessage = messages[messages.length - 1]
  return lastMessage.timestamp || lastMessage.createdAt
}

// 模型类型常量
export const MODEL_TYPES = {
  DEEPSEEK_CHAT: 'deepseek-chat',
  DEEPSEEK_REASONER: 'deepseek-reasoner',
  XUNFEI_CHAT: 'xunfei-chat',
  XUNFEI_REASONER: 'xunfei-reasoner'
}

// 模型类型中文映射
export const MODEL_TYPE_TEXT = {
  [MODEL_TYPES.DEEPSEEK_CHAT]: 'DeepSeek 对话',
  [MODEL_TYPES.DEEPSEEK_REASONER]: 'DeepSeek 推理',
  [MODEL_TYPES.XUNFEI_CHAT]: '星火 对话',
  [MODEL_TYPES.XUNFEI_REASONER]: '星火 推理'
}

// 获取模型类型文本
export const getModelTypeText = (modelType) => {
  return MODEL_TYPE_TEXT[modelType] || modelType
} 